package com.sbd.endpoint;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Component
@Endpoint(id = "database", enableByDefault = true)
public class DatabaseEndpoint {

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName = null;;

    @Value("${spring.datasource.url}")
    private String url = null;

    @Value("${spring.datasource.username}")
    private String username = null;

    @Value("${spring.datasource.password}")
    private String password = null;

    // 测试SQL
    private static final String TEST_SQL = "select 1 from dual";

    // 一个端点只能存在一个@ReadOperation标注的方法
    // 它代表的是HTTP的GET请求
    @ReadOperation
    public Map<String, Object> test() {
        Connection conn = null;
        Map<String, Object> msgMap = new HashMap<>();
        try {
            Class.forName(driverClassName);
            conn = DriverManager.getConnection(url, username, password);
            // 执行测试SQL
            conn.createStatement().executeQuery(TEST_SQL);
            msgMap.put("success", true);
            msgMap.put("message", "测试数据库连接成功");
        } catch (Exception ex) {
            msgMap.put("success", false);
            msgMap.put("message", ex.getMessage());
        } finally {
            if (conn != null) {
                try {
                    conn.close(); // 关闭数据库连接
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return msgMap;
    }
}
